package com.sunxd.zstudy.juc.T18_reference;

import org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeText;

import java.io.IOException;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 虚引用 -- get不到 操作堆外内存
 *  基本没用
 *
 * @author: 作者名称
 * @date: 2021-09-08 15:00
 **/
public class T18_4PhantomReference {

    private static final List<Object> LIST = new LinkedList<>();
    private static final ReferenceQueue<M> QUEUE = new ReferenceQueue<>();


    public static void main(String[] args) throws IOException, InterruptedException {
        PhantomReference<M> m = new PhantomReference<>(new M(),QUEUE);
        new Thread(()->{
            while (true) {
                LIST.add(new byte[1024 * 1024]);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(m.get());
            }
        }).start();
        new Thread( () -> {
            while (true) {
                Reference<? extends M> poll =QUEUE.poll();
                if(poll != null){
                    System.out.println("--虚引用被回收了--");
                }
            }
        }).start();
        System.in.read();


    }

}
